package alvarodelrosal.chat.server.infraestructura;

import alvarodelrosal.chat.server.modelo.ChatUser;
import java.util.ArrayList;
import java.util.List;

public class ChatUsersMemoryPersistence implements ChatUsersPersistence {
    
    private List<ChatUser> users = new ArrayList();
    private static ChatUsersPersistence persistence = null;
    
    private ChatUsersMemoryPersistence() {
        users.add(new ChatUser(1, "alvaro", "123456", "Alvaro", "alvarodelrosal@gmail.com", true));
    }
    
    public static ChatUsersPersistence getPersistence() {
        if (persistence == null) {
            persistence = new ChatUsersMemoryPersistence();
        }
        return persistence;
    }
    
    @Override
    public boolean existsTheUser(String username) {
        for (ChatUser user : users) {
            if (user.getUsername().equals(username)) {
                return true;
            }
        }
        return false;
    }
    
    @Override
    public boolean existsTheUser(String username, String password) {
        for (ChatUser user : users) {
            if (user.getUsername().equals(username) &&
                    user.getPassword().equals(password)) {
                return true;
            }
        }
        return false;
    }
    
    @Override
    public ChatUser getTheUser(String username, String password) {
        for (ChatUser user : users) {
            if (user.getUsername().equals(username) &&
                    user.getPassword().equals(password)) {
                return user;
            }
        }
        throw new IllegalArgumentException("User doesn't exists must check it before");
    }
    
    @Override
    public ChatUser getTheUser(int userId) {
        for (ChatUser user : users) {
            if (user.getUserId() == userId) {
                return user;
            }
        }
        return null;
    }
    
    @Override
    public void addUser(ChatUser user) {
        users.add(user);
    }
    
    @Override
    public void deleteUser(int userId) {
        ChatUser user = getTheUser(userId);
        if (existsThe(user)) {
            users.remove(this);
        }
    }

    private boolean existsThe(ChatUser user) {
        return user != null;
    }

    @Override
    public List<ChatUser> getAllUsers() {
        return users;
    }

}
